﻿using DAL;
using DAL.Dao;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using BLL;
using DAL.Models;
using ExpressManagement.Areas.BackSys.ServiceTools;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Mvc;
using AutoMapper;
using Microsoft.Extensions.Caching.Memory;
using BLL.Interface;
using ExpressManagement.Areas.BackSys.ServiceTools.Redis;
using Microsoft.EntityFrameworkCore;
using DAL.Models.DTO;

namespace ExpressManagement.Areas.BackSys.Controllers
{
    [Area("BackSys")]
    //[Route("api/[controller]")]
    //[ApiController]
 
    public class UserController : BaseController
    {
        // GET: UserInfo
        // GET: /BackSys/UserInfo/
        private readonly IUserinfoImpl _impl;
        private readonly IMemoryCache _memoryCache;
        private string keyStr = string.Empty;
        private string cache = string.Empty;
        private string serializeStr = string.Empty;
        public UserController(IMemoryCache _memoryCache, IUserinfoImpl _impl, RedisHelper redisHelper, ExpressDBContext _dbContext, IHttpContextAccessor httpContextAccessor, DbContextOptions<ExpressDBContext> _dbContextoptions, IMapper mapper, SignalRSender signalRSender)
            : base(mapper: mapper, signalRSender: signalRSender, httpContextAccessor: httpContextAccessor, _memoryCache: _memoryCache, redisHelper: redisHelper, _dbContext: _dbContext, dbContextOptions: _dbContextoptions)

        {
            //if (_impl == null) _impl = new UserinfoImpl();
            this._impl = _impl;

        }

        public async Task< IActionResult> UserManage()
        {

            //(var totalPages, var data) = _impl.GetList(Convert.ToInt16(MySession.GetSession("userRows")), Convert.ToInt16(MySession.GetSession("userPage")));
            //ViewBag.UserList = data;
            //MySession.WriteSession("userTotalPages", totalPages);
            return PartialView();
        }

        public async Task<IActionResult> UserUpdate()
        {
            return PartialView();
        }


        [HttpGet]
        //[ResponseCache(Duration = 10)]
        public async Task<IActionResult> ChangePage([FromQuery]int page)
        {
         
            IDictionary<string, string> set = new Dictionary<string, string>();
            int? rows = GetInt32FromSession("userRows");
            cache = GetCacheFromRedis<string>(EntityUserInfo, TypePage, page, LoginType);
            if (!string.IsNullOrEmpty(cache))
            {
                return Json(cache);
            }
            else
            {
                (var totalPages, var data) = _impl.GetList(rows.Value, page);
                FillSetAndSaveCache(totalPages, JsonConvert.SerializeObject(data), page, set, EntityUserInfo, TypePage, LoginType, out serializeStr);
                //set.Add("totalPages", totalPages.ToString());
                //set.Add("data", JsonConvert.SerializeObject(data));
                //serializeStr = JsonConvert.SerializeObject(set);
                //SetCacheOnRedis<string>(EntityUserInfo, TypePage, page.Value, LoginType, serializeStr);
                return Json(serializeStr);
            }

        }
        public async Task<IActionResult> List()
        {
            int page = 1;
            if (!string.IsNullOrWhiteSpace(Request.Form["userPage"]))
            {
                if (int.TryParse(Request.Form["userPage"], out page))
                {
                    if (page < 1)
                    {
                        page = 1;
                    }
                };
            }
            int rows = 10;
            if (!string.IsNullOrWhiteSpace(Request.Form["userRows"]))
            {
                if (int.TryParse(Request.Form["userRows"], out rows))
                {
                    if (rows < 10)
                    {
                        rows = 10;
                    }
                    else if (rows > 30)
                    {
                        rows = 30;
                    }
                }
            }
            return Json(new
            {
                rows = _impl.GetList(rows,page),
                total = _impl.ExistNum
            });
       
        }
        //
        // GET: /BackSys/UserInfo/Details/5
        [HttpGet]
        public async Task<IActionResult> GetItemByID([FromQuery]string id, [FromQuery] string action)
        {
            UserInfo? user = _impl.Find(Convert.ToInt32(id));
            //string get = MyRequest.GetQueryString();
            //Task obj = tool.DeserializeObject(get) as Task;
            if (user == null)
            {
                return Json(null);
            }
            string seri = JsonConvert.SerializeObject(user);
            return Json(seri);

        }

        //
        // GET: /BackSys/UserInfo/Create



        public  async Task<IActionResult> UserRegister()
        {
            return PartialView();
        }


        [HttpPost]
        public async Task<IActionResult> Add([FromForm] UserDTO entity)
        {
            UserInfo user = _mapper.Map<UserInfo>(entity);
            //user.UserName = Request.Form["UserName"];
            //user.UserPass = Request.Form["UserPass"];
            //user.TrueName = Request.Form["TrueName"];
            //user.Phone = Request.Form["Phone"];
            //user.Email = Request.Form["Email"];
            //user.Idcard = Request.Form["Idcard"];
            //user.ContactAddress = Request.Form["Address"];
            user.AddTime = DateTime.Now;
            if (_impl.Add(user))
            {
                RemoveRedisCacheEntity(EntityUserInfo, TypePage, LoginType);
                return Json(1);
            }
            return Json(0);
        }
        [HttpPost]
        public async Task<IActionResult> Update([FromForm] UserDTO entity)
        {
            UserInfo user = _mapper.Map<UserInfo>(entity);
            //user.Id = Convert.ToInt32(Request.Form["Id"]);
            //user.UserName = Request.Form["UserName"];
            //user.UserPass = Request.Form["UserPass"];
            //user.TrueName = Request.Form["TrueName"];
            //user.Phone = Request.Form["Phone"];
            //user.Email = Request.Form["Email"];
            //user.Idcard = Request.Form["Idcard"];
            //user.ContactAddress = Request.Form["Address"];
            user.UpdateTime = DateTime.Now;
            if (_impl.Update(user.Id, user)==true)
            {
                RemoveRedisCacheEntity(EntityUserInfo, TypePage, LoginType);
                return Json(1);
            }


            return Json(0);
        }

        //
        // POST: /BackSys/UserInfo/Edit/5



        // GET: /BackSys/UserInfo/Delete/5
        [HttpPost]
        public async Task<IActionResult> Delete(int id = 0)
        {
         
            if (_impl.Delete(id)==true)
            {
                RemoveRedisCacheEntity(EntityUserInfo, TypePage, LoginType);
                return Json(1);
            }
            return Json(0);
        }
        //
        // POST: /BackSys/UserInfo/Delete/5



    }
}